#!/usr/bin/python
"""
The uniqueness of an event is composed of it's start, endtime and summary. The script removes duplicate (based on that ID) events from a iCalendar file.
"""

import shutil
import sys
from datetime import datetime
import dateutil.parser
import pytz

DEFAULT_TIMEZONE = "Europe/Vienna"

def to_utc(tznaive_date, timezone):
    local = pytz.timezone(timezone)
    local_dt = tznaive_date.replace (tzinfo = local)
    local_dt.tzinfo.normalize(local_dt)
    return local_dt.astimezone(pytz.utc)

def parse_date(datestr):
    date_ = dateutil.parser.parse(datestr.split(":")[1])
    if not date_.tzinfo:
        try:
            tzabbr = datestr.split("TZID=")[1].split(":")[0]
        except IndexError:
            # no tzinfo given assume default
            tzabbr = DEFAULT_TIMEZONE
        date_ = to_utc(date_, tzabbr)            
    return date_
        

    
def main(file_):    
    lines = []
    entries = {}
    
    def lines_entries_index():
        for i,line in enumerate(lines):            
            if not isinstance(line, basestring):
                return i

    with file_ as f:
        eventline = False
        while 1:
            line = f.readline()
            if not line: break
            # sys.stderr.write(line)
            if line.startswith('BEGIN:VEVENT'):
                eventline = True
                if not lines_entries_index():
                    lines.append(entries)                    
                temp = []
            elif line.startswith('DTSTART'):            
                dtstart = parse_date(line).isoformat()
            elif line.startswith('DTEND'):            
                dtend = parse_date(line).isoformat()
            elif line.startswith('SUMMARY'):
                summary = line.split(":")[1]        
            elif line.startswith('END:VEVENT'):
                temp.append(line)
                id_ = str(dtstart) + str(dtend) + summary
                assert id_
                if id_ in entries:
                    sys.stderr.write("Duplicate: %s\n" % id_) 
                entries[id_] = "".join(temp)
                eventline = False
            else:
                if not eventline:
                    lines.append(line)
            if eventline:        
                temp.append(line)
                
    for line in lines:
        if isinstance(line, basestring):
            sys.stdout.write(line)
        else:
            for k, v in line.iteritems():
                sys.stdout.write(v)
            
    
if __name__ == "__main__":
    try:
        filename = sys.argv[1]
    except IndexError:
        main(sys.stdin)        
    else:
        main(file(filename))
    


